//
//  MainDefaulSearctVC.m
//  ZITHER
//
//  Created by weixin on 2018/11/19.
//  Copyright © 2018 weixn. All rights reserved.
//

#import "MainDefaulSearctVC.h"
#import "MainAntistopVC_V4.h"
#import "MainDefaulSearchVC_V4.h"
#import "MainDiscernVC.h"
#import "Ugc_Release_VC_WX_V4.h"
#import "MeRegisterLoginVC.h"

@interface MainDefaulSearctVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)BaseLab * lab;

@property (nonatomic,strong)BaseBtn * btnClause;

@property (nonatomic,strong)BaseBtn * btnShoot;

@property (nonatomic,strong)BaseBtn * btnHelp;//社区救助

@end

@implementation MainDefaulSearctVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (self.indexType == 2) {
        [self setNav];
        self.tbv.arrImageM = self.arrImageM;
    }else{
        [self.baseNavigationView setHiddenNav:YES VC:self];
        [self loadConditionDate];
    }
    
    [self setUI];
    [self.tbv reloadData];

    [self setRACObserve];
    
}

-(void)loadData{
    
    if (self.indexType == 2) {
        [self.tbv reloadData];
//        [self.tbv.mj_header endRefreshing];
//        [self.tbv.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
    /** 处理好数据传值 */
    NSDictionary *dic = [self setDicloadDate];
    NSString *sort = @"secondHandPrice,asc";
    if (self.search.btn3.tag == 300)   sort = @"secondHandPrice,desc";
    //sort
        [[serviceDefualt loadGoodsList:dic page:self.tbv.page sort:sort reponseObjctClass:[GoodsModel class]]subscribeNext:^(ResponseData* x) {
            GoodsModel *modelRes = x.responseData;
            NSLog(@"%@",x.responseRawData);
            if (x.success) {
                
                if (modelRes.goodVOs.count == 0) {

                    if (self.tbv.page == 0) {
                        [Tools showTips:@"没有搜到数据"];
                        [self.tbv.mj_header endRefreshing];
                        [self.tbv.mj_footer endRefreshing];
                        self.search.leb.text = @"0个搜索结果";
                        GoodsModel * goodVOsM = [[GoodsModel alloc]init];
                        self.tbv.model = goodVOsM;
                    }
                        [self.tbv.mj_footer endRefreshingWithNoMoreData];
                    
                }else{
                    if (self.tbv.page == 0) {
                        
                        self.tbv.model = modelRes;
                    
//                        self.search.leb.text = [NSString stringWithFormat:@"%@个搜索结果",modelRes.totalCount];
                        int priceInt = [modelRes.totalCount intValue];
                        
                        NSNumberFormatter *moneyFormatter = [[NSNumberFormatter alloc] init];
                        moneyFormatter.positiveFormat = @"###,##0";
                        NSString *formatString = [moneyFormatter stringFromNumber:@(priceInt)];
                        
                        self.search.leb.text = [NSString stringWithFormat:@"%@个搜索结果",formatString];
                    }else{
                        for (goodVOsModel *goodVOsModel1 in modelRes.goodVOs) {
                            [self.tbv.model.goodVOs addObject:goodVOsModel1];
                        }
                    }
                    
                }
                
            }else{
             
                [Tools showTips:x.errorInfo];
            }
            [self.tbv reloadData];

            [self.tbv.mj_header endRefreshing];
            [self.tbv.mj_footer endRefreshing];
        }];
}
    


-(NSMutableDictionary *)setDicloadDate{
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    
    if (![self.arrM[0] isEqualToString:@"价格范围"]) {
        [dic setValue:self.arrM[0] forKey:@"price"];
    }
    
    letterModel *model = self.arrM[1];
    if (![model.brandName isEqualToString:@"品牌"]) {
        [dic setValue:model.id forKey:@"brand"];
    }
    
    if (self.keyWord.length != 0) {
//        [dic setValue: [self.keyWord removeSpaceAndNewline] forKey:@"key_words"];
        [dic setValue:self.keyWord forKey:@"key_words"];

    }
    
    for (int i = 2; i<self.arrM.count; i++) {
        NSDictionary *dic1 = self.arrM[i];
        
        NSString *num = dic1[@"num"];
        if (num.length>0) {
            searchOptionVOsModel * VOsModel = self.model.searchOptionVOS[i-2];
            
            NSString *VodId = VOsModel.id;
            NSString *optionsID = VOsModel.options[[num integerValue]].id;

            [dic setValue:optionsID forKey:VodId];
        }
        
    }

    
    return dic;
    
}


-(void)setRACObserve{
    
    
    //当前页展示数据
    [RACObserve(self, arrM)subscribeNext:^(id  _Nullable x) {
        [self loadData];
    }];
    
    //条件寻表进来的数据原始数据
    [RACObserve(self, model)subscribeNext:^(id  _Nullable x) {
        [self loadData];
    }];
    
    //关键词 进来的数据
    [RACObserve(self, keyWord)subscribeNext:^(id  _Nullable x) {
        if (self.keyWord.length == 0) {
            [self.search.btn2 setTitle:@"  关键词搜索" forState:UIControlStateNormal];
        }else{
            [self.search.btn2 setTitle:self.keyWord forState:UIControlStateNormal];
        }
    }];
    
    //图片识别 图片识别进来的数据
    [RACObserve(self, arrImageM)subscribeNext:^(id  _Nullable x) {
        [self loadData];

    }];
}

-(void)setNav{
    [self.baseNavigationView setHiddenNav:NO VC:self];

    self.search.hidden = YES;
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.leftButton1.hidden = YES;
    self.baseNavigationView.isShowShadow = YES;
    self.baseNavigationView.navViewStyle.title.text = @"识别结果";
}

-(void)setUI{
    [self.view addSubview:self.search];
    self.search.backgroundColor = [UIColor randomColor];
    [self.search mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view).offset(0);
        make.height.offset(127);
    }];
    
    [self.view addSubview:self.tbv];

    if (self.indexType == 2) {
        [self.tbv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.equalTo(self.view).offset(0);
            make.top.equalTo(self.view.mas_top).offset(NaviHeight);
            make.height.offset(kScreenH-kBottomSafeHeight-40-NaviHeight-45);
            
        }];
        [self setImage];
    }else{
        [self.tbv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.right.left.equalTo(self.view).offset(0);
            make.height.offset(kScreenH-127);
        }];
    }

    
}

-(MainDefaulSearctVC_Tbv *)tbv{
    if (!_tbv) {
        if (self.indexType == 2) {
            _tbv = [[MainDefaulSearctVC_Tbv alloc]initializeFrame:CGRectMake(0, 0, 0, 0) isMj:0 isEstimatedRowHeight:YES addRegisterNib:@[@"MainDefaultTbCell"]];
            _tbv.indexType = self.indexType;
        }else{
            _tbv = [[MainDefaulSearctVC_Tbv alloc]initializeFrame:CGRectMake(0, 0, 0, 0) isMj:1 isEstimatedRowHeight:YES addRegisterNib:@[@"MainDefaultTbCell"]];
            _tbv.indexType = self.indexType;
        }
    }
    return _tbv;
}

-(MainDefaulSearctVC_SearchV *)search{
    if (!_search) {
        _search = [[MainDefaulSearctVC_SearchV alloc]initWithFrame:CGRectMake(0, 0, 2, 2)];
        
        /** 按钮点击案例 */
        @weakify(self);
        [[_search.btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            //展开选择器
            MainDefaulSearchVC_V4 *vc = [[MainDefaulSearchVC_V4 alloc]init];
            vc.indexType = 1;
            vc.tbv.arrM = self.arrM;
            vc.tbv.model = self.model;

            [vc setBlock:^(NSMutableArray * arrM) {
                
                self.arrM = arrM;
                [self loadData];
            }];
            [self.navigationController pushViewController:vc animated:YES];

        }];
        
        [[_search.btn2 rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);

            MainAntistopVC_V4 *vc = [[MainAntistopVC_V4 alloc]init];
            vc.indexType = 1;
            [vc setBlock:^(NSString * _Nonnull str) {
                self.keyWord = str;
                [self loadData];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
        [[_search.btn3 rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            self.search.btn3.selected =  !self.search.btn3.selected;
            //排序按钮
            if ( self.search.btn3.tag==300) {
                self.search.btn3.tag = 3001;
//                [self.search.btn3 setImage:[UIImage imageNamed:@"nav_btn_ascend"] forState:UIControlStateNormal];
            }else{
                self.search.btn3.tag = 300;
//                [self.search.btn3 setImage:[UIImage imageNamed:@"nav_btn_descend"] forState:UIControlStateNormal];
            }
            [self.search chageBtn];
            [self loadData];
        }];
        

    }
    return _search;
}



/** 图片识别展示 */
-(void)setImage{
    [self.view addSubview:self.lab];
    [self.view addSubview:self.btnShoot];
    [self.view addSubview:self.btnHelp];
    [self.view addSubview:self.btnClause];
    
    
    [self.lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_centerX).offset(-80);
        make.top.equalTo(self.btnShoot.mas_bottom).offset(15);
    }];
    
    [self.btnHelp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.btnShoot.mas_top).offset(-10);
        make.right.equalTo(self.view).offset(-15);
        make.left.equalTo(self.view).offset(15);
        make.height.mas_offset(45);
    }];
    
    [self.btnShoot mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-kBottomSafeHeight-60);
        make.right.equalTo(self.view).offset(-15);
        make.left.equalTo(self.view).offset(15);
        make.height.mas_offset(45);
    }];
    
    [self.btnClause mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lab.mas_centerY).offset(0);
        make.left.equalTo(self.lab.mas_right).offset(5);
    }];
    
}

-(BaseBtn *)btnShoot{
    if (!_btnShoot) {
//        _btnShoot = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:@"重新拍摄" NormalTextColor:baseColorTheme SeleText:@"" SeleTextColor:baseColorTheme  font:15 isBold:NO];
        _btnShoot = [BaseBtn initCustomBtnImageAndTitles:@[@"在试一次"] images:@[@"识别结果_再试一次"] color:@[baseColorTheme]];
        
        [_btnShoot setCornerRadiusWithRadius:4 isMasks:YES];
        [_btnShoot setBorderWithColor:baseColorTheme width:1];
        /** 按钮点击案例 */
        @weakify(self);
        [[_btnShoot rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    return _btnShoot;
}

-(BaseBtn *)btnHelp{
    if (!_btnHelp) {
        _btnHelp = [BaseBtn initCustomBtnImageAndTitles:@[@"社区求助"] images:@[@"识别结果_#"] color:@[baseColorTheme]];
        [_btnHelp setCornerRadiusWithRadius:4 isMasks:YES];
        [_btnHelp setBorderWithColor:baseColorTheme width:1];
        /** 按钮点击案例 */
        @weakify(self);
        [[_btnHelp rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [[serviceDefualt loadTopicDefaultSubjecte:nil]subscribeNext:^(ResponseData* x) {
                if (x.success) {
                    Ugc_Release_VC_WX_V4 *vc = [[Ugc_Release_VC_WX_V4 alloc]init];
                    vc.id = x.responseRawData[@"data"][@"id"];
                    vc.Topictitle = x.responseRawData[@"data"][@"title"];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [Tools showTips:x.errorInfo];
                }
            }];
      
        }];
    }
    return _btnHelp;
}

-(BaseLab *)lab{
    if (!_lab) {
        _lab = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 0, 0) text:@"我是表友! " font:14 textColor:[UIColor blackColor] isBold:NO numberOfLines:0];
        _lab.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:14];
    }
    return _lab;
}

-(BaseBtn *)btnClause{
    if (!_btnClause) {
//        _btnClause = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:@"拍个短视频，帮助完善数据库" NormalTextColor:baseColorTheme SeleText:@"" SeleTextColor:baseColorTheme  font:14 isBold:NO];
        
        _btnClause = [BaseBtn initCustomBtnImageAndTitles:@[@"拍个短视频，帮助完善数据库"] images:@[] color:@[baseColorTheme]];
//@"识别结果_icon"
        _btnClause.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:14];
        _btnClause.backgroundColor = [UIColor clearColor];
        _btnClause.tag = 211;//当不为211时候 点击事件可以不需要判断是否登录
//        _btnClause.imageView.contentMode = UIViewContentModeScaleAspectFit;
//        [_btnClause sizeToFit];
//        _btnClause.titleEdgeInsets = UIEdgeInsetsMake(0, -100, 0, 0);
//        _btnClause.imageEdgeInsets = UIEdgeInsetsMake(0, 150, 0, 0);
        
        /** 按钮点击案例 */
        @weakify(self);
        [[_btnClause rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            
            if (!kUSER_INFO_MANAGER.userIsLogin) {
                if (self.btnClause.tag !=211) {
                    MainDiscernVC *vc = [[MainDiscernVC alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                    return ;
                }
                NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"登录可参与腕表视频悬赏活动，是否登录？"];
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不用" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    self.btnClause.tag = 212;
                }];
                UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    [self.navigationController pushViewController:[[MeRegisterLoginVC alloc]init] animated:YES];
                }];
                // Add the actions.
                
                [alertController addAction:cancelAction];
                
                [alertController addAction:otherAction];
                
                [self.navigationController presentViewController:alertController animated:YES completion:nil];
                return ;
            }
            MainDiscernVC *vc = [[MainDiscernVC alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }
    return _btnClause;
}


-(void)setArrImageM:(NSMutableArray *)arrImageM{
    _arrImageM = arrImageM;
    if (self.arrImageM.count == 0) {
        [self.tbv setNoMoreDataBg:NO NoDataState:2];
        self.btnClause.hidden = NO;
        self.lab.hidden = NO;
        self.btnShoot.hidden = NO;
        self.view.backgroundColor = [UIColor colorWithHex:@"F5F5F5"];
        [self.tbv.mj_footer endRefreshingWithNoMoreData];
    }
//    if (self.indexType == 2) {
//  
//    }else{
//        [self.tbv setNoMoreDataBg:YES NoDataState:2];
//        self.btnClause.hidden = NO;
//        self.lab.hidden = NO;
//        self.btnShoot.hidden = NO;
//        self.view.backgroundColor = [UIColor whiteColor];
//    }
//    self.indexType = 1;
}




/** 加载网络寻表条件 */
-(void)loadConditionDate{
    
    [[serviceDefualt loadGoodsSearchConditions:[searchConditionsModel class]]subscribeNext:^(ResponseData * x) {
        if (x.success) {
            [self setLoadModel:x.responseData];
        }
    }];
}


-(void)setLoadModel:(searchConditionsModel *)model{
    
    self.model = model;
    NSLog(@"");
    
//    NSArray *arr = model.searchOptionVOS;
    
//    [self.arrM addObject:@"不限"];
//    [self.arrM addObject:@"品牌"];
//
//    for (searchOptionVOsModel *model in arr) {
//        NSMutableArray *arrM1 = [[NSMutableArray alloc]init];
//        optionssModel *model2  = [[optionssModel alloc]init];
//        model2.name = @"不限";
//        [arrM1 addObject:model2];
//
//        for (optionssModel *model1 in  model.options) {
//            [arrM1 addObject: model1];
//        }
//
//        [self.arrM addObject:arrM1];
//    }
//
//    [self.tbv reloadData];
}

@end
